﻿//产品销售单，主细表表单
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using HF.BaseWebCtrlLib;
using HF.Business.Common;//一个业务模块的公共类
using HF.Framework.Web;//框架类
using HF.WorkFlow.Const;
using HF.Framework.DataClientDBAgent;

using HF.Business.Sale;//封装销售业务的类

public partial class SaleRetailEdit : BaseUserControl//继承基类
{
    DataTable SaleDetTable;//明细表变量
    string SnSaleDet = "";//session值,用session来缓存明细表
    protected void Page_Load(object sender, EventArgs e)
    {
      
        base.Page_Load();//继承基类的方法，可以控制表单中控件的enbale属性和readonly属性
        SnSaleDet = WorkflowInsId;//
        if (CtrlState == WorkFlowConst.STATE_VIEW)//控制编辑区是否显示
        {
            Panel1.Visible = false;
            Panel2.Visible = false;
            Panel3.Visible = false;
        }
        else
        {
            Panel1.Visible = true; 
            Panel2.Visible = true;
            Panel3.Visible = true;
        }
        if (!IsPostBack)
        {
            initData();
            initSourceBill(); 
            
          
        }
        SaleDetTable = (DataTable)Session[SnSaleDet];//读取缓存中的数据
       
        
    }
    private void initSourceBill()
    {
        DataTable dt = SaleIndent.SaleIndentBillNoRetail();
        string tmpStr = "";
        ListItem l = new ListItem("请选择销售订单", "###");
       this.drpSourceBill.Items.Add(l);
        foreach (DataRow dr in dt.Rows)
        {
            tmpStr = dr["Bill_Code"].ToString() + "|" + dr["Customer_Code"].ToString() + "|" + dr["Customer_Caption"].ToString() + "|" + dr["Bill_Caption"].ToString();
            l = new ListItem(tmpStr, dr["workflowInsId"].ToString());
            drpSourceBill.Items.Add(l);
        }
    }
    /// <summary>
    /// 选择销售订单
    /// </summary>
    private void loadSourceBill(string ikey)
    {

        DataTable SaleIndentDt = SaleIndent.GetSale_V_Indent(ikey);
        if (SaleIndentDt != null && SaleIndentDt.Rows.Count > 0)//从订单中读取数据
        {
            double leaveNum = 0.00;
            SaleDetTable.Clear();
            tbxSourceCode.Text = SaleIndentDt.Rows[0]["Bill_Code"].ToString();
            tbxCustomerCode.Text = SaleIndentDt.Rows[0]["Customer_Code"].ToString();
            tbxCustomerCaption.Text = SaleIndentDt.Rows[0]["Customer_Caption"].ToString();
            foreach (DataRow drindent in SaleIndentDt.Rows)
            {

                leaveNum = Convert.ToDouble(drindent["Bill_LeaveNum"]);//剩余数量
                if (leaveNum > 0)//剩余数量>0
                {
                    DataRow dr = SaleDetTable.NewRow();
                    dr["WorkflowId"] = WorkflowId;
                    dr["WorkflowInsId"] = WorkflowInsId;
                    dr["WorktaskId"] = WorktaskId;
                    dr["WorktaskInsId"] = WorktaskInsId;
                    dr["Bill_Code"] = tbxBillCode.Text;
                    dr["Product_Code"] = drindent["Product_Code"].ToString();
                    dr["Product_Caption"] = drindent["Product_Caption"].ToString();
                    dr["Product_Type"] = drindent["Product_Type"].ToString();
                    dr["Product_Unit"] = drindent["Product_Unit"].ToString();
                    dr["Bill_Num"] = drindent["Bill_LeaveNum"].ToString();
                    dr["Bill_Price"] = drindent["Bill_Price"].ToString();
                    dr["Bill_dRebate"] = drindent["Bill_dRebate"].ToString();
                    dr["Bill_dMemo"] = drindent["Bill_dMemo"].ToString();
                    dr["Dept_Code"] = SaleStock.GetDefalutStoreCode(UserId);//默认仓库
                    dr["Bill_dMoney"] = Math.Round(Convert.ToDouble(dr["Bill_Num"]) * Convert.ToDouble(dr["Bill_Price"]) * Convert.ToDouble(dr["Bill_dRebate"]), 2) / 100;
                    SaleDetTable.Rows.Add(dr);
                }
            }
            billTotal();
            DataBindSource();
        }
        else
        {
            WorkDialog.ShowMessage(this.Page,"销售订单中没有未售完的信息!");
        }
    }
    /// <summary>
    /// 表单数据展现,考虑退回和草稿两种情况
    /// </summary>
    private void initData()
    {
       
        DataTable SaleRetailDt = SaleRetail.GetSaleRetailTable(WorkflowInsId);
        if (SaleRetailDt != null && SaleRetailDt.Rows.Count > 0)//检查是否有数据，如果有读取数据库中的数据
        {
            SaleRetail sr = new SaleRetail();
            sr.GetSaleRetailInfo(WorkflowInsId);
            tbxBillCode.Text = sr.Bill_Code;
            YYscBillDate.Text = sr.Bill_CreateDate;
            tbxBillMan.Text = sr.Bill_CreateName;
            tbxCustomerCode.Text = sr.Customer_Code;
            tbxCustomerCaption.Text = sr.Customer_Caption;
            tbxBillMoney.Text = sr.Bill_Money.ToString();
            tbxBillrMoney.Text = sr.Bill_rMoney.ToString();
            tbxBillsMoney.Text = sr.Bill_sMoney.ToString();
            tbxSourceCode.Text = sr.Bill_Source;
            YYscAccountDate.Text = sr.Bill_AccountDate;
            tbxMemo.Text = sr.Bill_Memo;
            SaleDetTable = SaleRetailDet.GetSaleRetailDet(WorkflowInsId);
        }
        else//如果没有初始化表单
        {
            string billType = "SXXX";
            tbxBillCode.Text = billType + BusinessComm.GetBillCode(billType);
            YYscBillDate.Text = BusinessComm.GetNowDate();
            YYscAccountDate.Text = BusinessComm.GetAddDaysDate(10);
            tbxBillMan.Text = this.UserName;
            ClientDBAgent agent = new ClientDBAgent();
            SaleDetTable =agent.GetBlankTable("Sale_V_Retail");
 
        }
        GridView1.DataSource = SaleDetTable;
        GridView1.DataBind();
        Session.Add(SnSaleDet, SaleDetTable);
    }
    /// <summary>
    /// 绑定数据
    /// </summary>
    private void DataBindSource()
    {
        GridView1.DataSource = SaleDetTable;
        GridView1.DataBind();
        Session.Add(SnSaleDet, SaleDetTable);
     
    }
    /// <summary>
    /// 查询产品信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        drpSearch.Items.Clear();
        if (rbtCode.Checked)
        {
            DataTable dt = Product.GetProductTableLikeId(tbxSearch.Text);
            string tmpStr = "";
            ListItem l = new ListItem("请选择输入", "###");
            drpSearch.Items.Add(l);
            foreach (DataRow dr in dt.Rows)
            {
               
                tmpStr = dr["Product_Code"].ToString() + "|" + dr["Product_Caption"].ToString() + "|" + dr["Product_Type"].ToString() + "|" + dr["Product_Unit"].ToString();
                l = new ListItem(tmpStr, dr["Product_Code"].ToString());
                drpSearch.Items.Add(l);
            }
        }
        else
        {
            DataTable dt = Product.GetProductTableLikeName(tbxSearch.Text);
            string tmpStr = "";
            ListItem l = new ListItem("请选择输入", "###");
            drpSearch.Items.Add(l);
            foreach (DataRow dr in dt.Rows)
            {
                tmpStr = dr["Product_Code"].ToString() + "|" + dr["Product_Caption"].ToString() + "|" + dr["Product_Type"].ToString() + "|" + dr["Product_Unit"].ToString();
                l = new ListItem(tmpStr, dr["Product_Code"].ToString());
                drpSearch.Items.Add(l);
            }
        }
    }
    /// <summary>
    /// 选择输入产品
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpSearch_SelectedIndexChanged(object sender, EventArgs e)
    {
        string id = drpSearch.SelectedValue;
        DataTable dt = Product.GetProductTableById(id);
        if (dt != null && dt.Rows.Count > 0)
        {
            tbxProductCode.Text = dt.Rows[0]["Product_Code"].ToString();
            tbxProductCaption.Text = dt.Rows[0]["Product_Caption"].ToString();
            tbxProductType.Text = dt.Rows[0]["Product_Type"].ToString();
            tbxProductUnit.Text = dt.Rows[0]["Product_Unit"].ToString();
            tbxProdutPrice.Text = dt.Rows[0]["Product_Price"].ToString();
            tbxProductQty.Text = "0.00";
            tbxRebate.Text = "100";
            tbxProductMoney.Text = "0.00";
        }
    }
    /// <summary>
    /// 汇总金额
    /// </summary>
    /// <returns></returns>
    private void  sumTotal(out double billmoney,out double billrmoney)
    {
        billmoney = 0.00; billrmoney = 0.00;
        foreach (DataRow dr in SaleDetTable.Rows)
        {
            billmoney =billmoney+ Math.Round(Convert.ToDouble(dr["Bill_Num"]) * Convert.ToDouble(dr["Bill_Price"]));
            billrmoney = billrmoney + Convert.ToDouble(dr["Bill_dMoney"]);
        }
      
 
    }
    /// <summary>
    /// 单据汇总
    /// </summary>
    private void billTotal()
    {
        double billmoney = 0.00,billrmoney=0.00;
        sumTotal(out billmoney,out billrmoney);
        tbxBillMoney.Text = billmoney.ToString();
        tbxBillrMoney.Text = billrmoney.ToString();
        tbxBillsMoney.Text = tbxBillrMoney.Text;
    }
    /// <summary>
    /// 添加产品信息到gridview中
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            if (tbxProductCode.Text.Length == 0)
            {
                WorkDialog.ShowMessage(this.Page, "请先选择产品!");
                return;
            }
            if (Convert.ToDouble(tbxProductQty.Text)==0)
            {
                WorkDialog.ShowMessage(this.Page, "数量不能为零!");
                return;
            }
            if (Convert.ToDouble(tbxProdutPrice.Text) == 0)
            {
                WorkDialog.ShowMessage(this.Page, "单价不能为零!");
                return;
            }
            DataRow dr = SaleDetTable.NewRow();
            dr["WorkflowId"] = WorkflowId;
            dr["WorkflowInsId"] = WorkflowInsId;
            dr["WorktaskId"] = WorktaskId;
            dr["WorktaskInsId"] = WorktaskInsId;
            dr["Bill_Code"] = tbxBillCode.Text;
            
            dr["Product_Code"] = tbxProductCode.Text;
            dr["Product_Caption"] = tbxProductCaption.Text;
            dr["Product_Type"] = tbxProductType.Text;
            dr["Product_Unit"] = tbxProductUnit.Text;
            dr["Bill_Num"] = tbxProductQty.Text;
            dr["Bill_Price"] = tbxProdutPrice.Text;
            dr["Bill_dRebate"] = tbxRebate.Text;
            dr["Bill_dMemo"] = tbxProductMemo.Text;
            dr["Dept_Code"] = SaleStock.GetDefalutStoreCode(UserId);//默认仓库
            dr["Bill_dMoney"] = Math.Round(Convert.ToDouble(dr["Bill_Num"]) * Convert.ToDouble(dr["Bill_Price"]) * Convert.ToDouble(dr["Bill_dRebate"]), 2)/100;
            SaleDetTable.Rows.Add(dr);
            tbxProductMoney.Text = dr["Bill_dMoney"].ToString();
            billTotal();
            DataBindSource();
        }
        catch (Exception ex)
        {
            WorkDialog.ShowMessage(this.Page,"增加失败:"+ex.Message.ToString());
        }

    }
    /// <summary>
    /// 修改选择的产品信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnModify_Click(object sender, EventArgs e)
    {
        try
        {
            if (tbxProductCode.Text.Length == 0)
            {
                WorkDialog.ShowMessage(this.Page, "请先选择产品!");
                return;
            }
            if (Convert.ToDouble(tbxProductQty.Text) == 0)
            {
                WorkDialog.ShowMessage(this.Page, "数量不能为零!");
                return;
            }
            if (Convert.ToDouble(tbxProdutPrice.Text) == 0)
            {
                WorkDialog.ShowMessage(this.Page, "单价不能为零!");
                return;
            }
            DataRow dr = SaleDetTable.Rows[GridView1.SelectedIndex];
            dr["WorkflowId"] = WorkflowId;
            dr["WorkflowInsId"] = WorkflowInsId;
            dr["WorktaskId"] = WorktaskId;
            dr["WorktaskInsId"] = WorktaskInsId;
            dr["Product_Code"] = tbxProductCode.Text;
            dr["Product_Caption"] = tbxProductCaption.Text;
            dr["Product_Type"] = tbxProductType.Text;
            dr["Product_Unit"] = tbxProductUnit.Text;
            dr["Bill_Num"] = tbxProductQty.Text;
            dr["Bill_Price"] = tbxProdutPrice.Text;
            dr["Bill_dRebate"] = tbxRebate.Text;
            dr["Dept_Code"] = SaleStock.GetDefalutStoreCode(UserId);//默认仓库
            dr["Bill_dMemo"] = tbxProductMemo.Text;
            dr["Bill_dMoney"] = Math.Round(Convert.ToDouble(dr["Bill_Num"]) * Convert.ToDouble(dr["Bill_Price"]) * Convert.ToDouble(dr["Bill_dRebate"]), 2)/100;
            
            tbxProductMoney.Text = dr["Bill_dMoney"].ToString();
            DataBindSource();
            billTotal();
           
        }
        catch (Exception ex)
        {
            WorkDialog.ShowMessage(this.Page, "修改失败:" + ex.Message.ToString());
        }

    }
    /// <summary>
    /// 保存明细表
    /// </summary>
    private void saveSaleRetailDet()
    {
        SaleRetailDet.DeleteByWorkflowInsId(WorkflowInsId);//首先删除已有的数据
        foreach (DataRow dr in SaleDetTable.Rows)
        {
            SaleRetailDet srd = new SaleRetailDet();
            srd.Bill_ID = Guid.NewGuid().ToString();
            srd.WorkflowId = dr["WorkflowId"].ToString();
            srd.WorkflowInsId = dr["WorkflowInsId"].ToString();
            srd.WorktaskId = dr["WorktaskId"].ToString();
            srd.WorktaskInsId = dr["WorktaskInsId"].ToString();
            srd.Bill_Code = dr["Bill_Code"].ToString();
            srd.Product_Code = dr["Product_Code"].ToString();
            srd.Bill_Num = Convert.ToDouble(dr["Bill_Num"]);
            srd.Bill_Price = Convert.ToDouble(dr["Bill_Price"]);
            srd.Dept_Code = dr["Dept_Code"].ToString();
            srd.Bill_dMemo = dr["Bill_dMemo"].ToString();
            srd.Bill_dMoney = Convert.ToDouble(dr["Bill_dMoney"]);
            srd.Bill_dRebate = Convert.ToDouble(dr["Bill_dRebate"]);
            srd.Insert();
        }
    }
    /// <summary>
    /// 表单数据提交
    /// </summary>
    public override void SaveUserControl(bool IsDraft)
    {
        base.SaveUserControl(IsDraft);
        SaleRetail sr = new SaleRetail();
        sr.WorkflowId = WorkflowId;
        sr.WorkflowInsId = WorkflowInsId;
        sr.WorktaskId = WorktaskId;
        sr.WorktaskInsId = WorktaskInsId;
        sr.Bill_Code = tbxBillCode.Text;
        sr.Bill_CreateDate = YYscBillDate.Text;
        sr.Bill_CreateName = tbxBillMan.Text;
        sr.Bill_Source = tbxSourceCode.Text;
        sr.Customer_Code = tbxCustomerCode.Text;
        sr.Bill_Money = Convert.ToDouble(tbxBillMoney.Text);
        sr.Bill_rMoney = Convert.ToDouble(tbxBillrMoney.Text);
        sr.Bill_sMoney = Convert.ToDouble(tbxBillsMoney.Text);
        sr.Bill_Memo = tbxMemo.Text;
        sr.Bill_AccountDate = YYscAccountDate.Text;

        DataTable SaleRetaildt = SaleRetail.GetSaleRetailTable(WorkflowInsId);
        if (SaleRetaildt != null && SaleRetaildt.Rows.Count > 0)
        {
            sr.Update();//保存销售单主表信息
        }
        else
        {
            sr.Insert();//保存销售单主表信息
        }
        saveSaleRetailDet();//保存销售单明细表信息
      

    }
   /// <summary>
    ///  选中产品一条产品信息
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow gvr = GridView1.SelectedRow;
        tbxProductCode.Text=gvr.Cells[1].Text;
        tbxProductCaption.Text = gvr.Cells[2].Text;
        tbxProductType.Text = gvr.Cells[3].Text;
        tbxProductUnit.Text = gvr.Cells[4].Text;
        tbxProductQty.Text = gvr.Cells[5].Text;
        tbxProdutPrice.Text = gvr.Cells[6].Text;
        tbxRebate.Text = gvr.Cells[7].Text;
        tbxProductMoney.Text = gvr.Cells[8].Text;
        tbxProductMemo.Text = gvr.Cells[9].Text;
        
    }

   /// <summary>
   /// 删除一条产品信息
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (CtrlState == WorkFlowConst.STATE_VIEW) return;
        SaleDetTable.Rows.Remove(SaleDetTable.Rows[e.RowIndex]);
        billTotal();
        DataBindSource();
    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (drpSourceBill.SelectedIndex > 0)
        {
            loadSourceBill(drpSourceBill.SelectedValue);
        }
     
    }
    protected void btnReceiveMoney_Click(object sender, EventArgs e)
    {
      string p=  "SaleRetailMgr.aspx";
        Response.Write("<script>window.open('"+p+"','_blank')</script>");
    }
}
